package com.zelin.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zelin.common.to.es.SkuEsModel;
import com.zelin.gulimall.search.config.GulimallElasticSearchConfig;
import com.zelin.gulimall.search.constant.EsConstant;
import com.zelin.gulimall.search.service.GulimallSearchService;
import com.zelin.gulimall.search.vo.SearchParam;
import com.zelin.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.ParsedAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by WF on 2021/1/18 17:19
 * 谷粒mall搜索服务
 */
@Service
public class GulimallSearchServiceImpl implements GulimallSearchService {
    @Autowired
    private RestHighLevelClient highLevelClient;

    //1.根据传入的参数搜索商品
    @Override
    public SearchResult search(SearchParam param) {
        try {
            //1.1)根据查询参数得到SearchRequest对象
            SearchRequest searchRequest = buildSearchRequrest(param);
            SearchResponse searchResponse = highLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);


            //1.2)将查询得到的searchResponse对象返回得到的结果
            SearchResult searchResult = getSearchResult(searchResponse,param);
            for (SearchResult.AttrVo attr : searchResult.getAttrs()) {
                System.out.println(attr);
            }
            System.out.println("-------------------------------------------------------------------------------");
            for (SearchResult.BrandVo brand : searchResult.getBrands()) {
                System.out.println(brand);
            }
            System.out.println("-------------------------------------------------------------------------------");
            for (SearchResult.CatalogVo catalog : searchResult.getCatalogs()) {
                System.out.println(catalog);
            }
            System.out.println("-------------------------------------------------------------------------------");
            for (SkuEsModel product : searchResult.getProducts()) {
                System.out.println(product);
            }
            return searchResult;
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 根据查询参数生成SearchRequest参数
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequrest(SearchParam param) {
        //1.定义查询索引
        String[] indices = {EsConstant.PRODUCT_INDEX};
        //2.构建查询原对象
        SearchSourceBuilder sourceBuilder= new SearchSourceBuilder(); //构建DSL语句的
        //3.查询：过滤（按照属性，分类，品牌，价格区间，库存）
        //3.1)得到布尔查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //3.2)根据查询条件有值确定查询条件
        //3.2.1)模糊查询
        if(StringUtils.isNotBlank(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //3.2.2)过滤查询一：按照分类id查询
        if(param.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //3.2.3)过滤查询二：按照品牌id查询
        if(param.getBrandId() != null && param.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId())); //这里param.getBrandId()是数组一定要用termsQuery()查询，不能用termQuery()
        }
        //3.2.4)过滤查询三：按照指定的属性查询：//类似格式attrs=1_5寸:8寸&attrs=2_16G:8G
        if(param.getAttrs() != null && param.getAttrs().size() > 0){
            for (String attr : param.getAttrs()) {  //attr:是1_5寸:8寸这种格式
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");   //得到属性的值
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId)); //设置属性的值
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));//设置属性的值
                //定义嵌入式的查询构建器
                NestedQueryBuilder nestQueryBuilder = new NestedQueryBuilder("attrs",nestedboolQuery, ScoreMode.None);
                //将查询构建器添加到boolQueryBuilder中
                boolQueryBuilder.filter(nestQueryBuilder);
            }
        }
        //3.2.5)根据是否有库存进行查询
        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() == 1));  //param.getHasStock()==1，代表有库存，0代表没有库存
        //3.2.6)按照价格区间进行查询，价格格式：//1_500/_500/500_
        //判断是否有值
        String skuPrice = param.getSkuPrice();
        //定义范围区间查询构建器
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
        if(StringUtils.isNotBlank(skuPrice)){
            String[] s = skuPrice.split("_");
            if(skuPrice.startsWith("_")){
                rangeQueryBuilder.lte(s[1]);
            }else if(skuPrice.endsWith("_")){
                rangeQueryBuilder.gte(s[0]);
            }else{
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }
        }
        //添加价格范围查询到boolQueryBuilder中
        boolQueryBuilder.filter(rangeQueryBuilder);


        //把以前所有的查询都封装到sourceBuilder中
        sourceBuilder.query(boolQueryBuilder);

        //3.3)排序、分页、高亮
        //3.3.1)排序查询, 格式为：hotScore_asc/desc
        String sort = param.getSort();
        if(StringUtils.isNotBlank(sort)){
            String[] s = sort.split("_");
            //① 定义排序
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            //② 进行排序
            sourceBuilder.sort(s[0],order);
        }

        //3.3.2)进行分页查询
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //3.3.3)进行高亮查询
        if(StringUtils.isNotBlank(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");                 //设置高亮字段
            highlightBuilder.preTags("<b style='color:red'>");  //设置高亮查询的前缀
            highlightBuilder.postTags("</b>");                  //设置高亮查询的后缀
            sourceBuilder.highlighter(highlightBuilder);
        }

        //3.4)聚合分析
        //3.4.1)品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //3.4.1.1)添加品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //3.4.1.2)将品牌聚合添加到sourceBuilder中进行聚合
        sourceBuilder.aggregation(brand_agg);

        //3.4.2)分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3.4.3)属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        String s = sourceBuilder.toString();
        System.out.println("构建的DSL:" + s);
        return new SearchRequest(indices, sourceBuilder);
    }

    public static void main(String[] args) {
        String str = "_500";
        int length = str.split("_").length;
        System.out.println("length = " + length);

    }
    /**
     * 3. 根据查询响应对象得到查询结果对象
     * @param searchResponse
     * @return
     */
    private SearchResult getSearchResult(SearchResponse searchResponse,SearchParam param) {
        //第一部分：处理商品结果列表
        //1.1)定义返回的响应结果对象
        SearchResult searchResult = new SearchResult();
        //1.2)定义存放商品的列表集合
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        //1.3)处理商品将商品族到商品集合中
        if(hits.getHits() != null && hits.getHits().length > 0)
        for (SearchHit hit : hits.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            //处理高亮
            if(StringUtils.isNotBlank(param.getKeyword())){
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                String s = skuTitle.getFragments()[0].string();
                skuEsModel.setSkuTitle(s);
            }
            skuEsModels.add(skuEsModel);
        }
        //1.4)将商品集合与响应结果中的商品集合进行绑定
        searchResult.setProducts(skuEsModels);

        //第二部分：处理各种聚合
        //2.1)处理属性聚合
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> buckets = attr_id_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //2.1.1）得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //2.1.2) 得到属性的名字
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            //2.1.3) 得到属性的值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = new ArrayList<>();;
            for (Terms.Bucket attrBucket : attr_value_agg.getBuckets()) {
                String value = attrBucket.getKeyAsString();
                attrValues.add(value);
            }
            //2.1.4)为attrVo设置值
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            //2.1.5)将attrVo添加到集合中
            attrs.add(attrVo);
        }
        searchResult.setAttrs(attrs);

        //2.2)处理分类聚合
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();

            String catalogId = bucket.getKeyAsString();//分类id
            //分类名称
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().get("catalog_name_agg")).getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            catalogVo.setCatalogName(catalogName);
            catalogs.add(catalogVo);
        }
        searchResult.setCatalogs(catalogs);
        //2.3)处理品牌聚合
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = bucket.getKeyAsNumber().longValue(); //品牌id
            //品牌名称
            String brandName = ((ParsedStringTerms) (bucket.getAggregations().get("brand_name_agg"))).getBuckets().get(0).getKeyAsString();
            String brandImg = ((ParsedStringTerms) (bucket.getAggregations().get("brand_img_agg"))).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        //第三部分：处理分页信息
        long total = hits.getTotalHits().value;
        searchResult.setPageNum(param.getPageNum());    //设置当前页
        searchResult.setTotal(total);                   //设置总记录数
        int totalPages = (int)Math.ceil(total/(double)EsConstant.PRODUCT_PAGESIZE);
        searchResult.setTotalPages(totalPages);


        return searchResult;
    }
}
